import * as types from '../actionTypes/todos';

// 初始化 state
// state默认值：
const initialState = [
  { id: 1, text: '吃饭', done: true },
  { id: 2, text: '睡觉', done: false },
  { id: 3, text: '敲代码', done: true },
];

export const todos = (state = initialState, action) => {
  // 处理数据
  // 删除一个todo
  if (action.type === types.DEL_TODO) {
    // 返回一个删除后的数组
    // console.log('reducer', action);
    // 新建数组返回
    const filtered = state.filter((item) => item.id !== action.payload);
    // console.log('filtered', filtered);
    return filtered;
    // 切换 todo 状态
  } else if (action.type === types.TOGGLE_TODO) {
    return state.map((item) => {
      if (item.id === action.payload) {
        return { ...item, done: !item.done };
      }
      return item;
    });
    // 添加 todo
  } else if (action.type === types.ADD_TODO) {
    // console.log(action);
    return [
      ...state,
      { id: state.length + 1, text: action.payload, done: false },
    ];
    // 切换所有任务的选中状态
  } else if (action.type === types.TOGGLE_ALL) {
    // console.log(action);
    return state.map((item) => ({ ...item, done: action.payload }));
    // 清除已完成
  } else if (action.type === types.CLEAR_DONE) {
    // console.log(action);
    // 把未完成的过滤出来
    return state.filter((item) => !item.done);
    // 更新任务
  } else if (action.type === types.UPDATE_TODO) {
    // console.log(action);
    return state.map((item) => {
      if (item.id === action.payload.id) {
        return { ...item, text: action.payload.text };
      }
      return item;
    });
  } else {
    return state;
  }
};
